package com.zhang.crm.handler;

import com.zhang.crm.constant.Constants;
import com.zhang.crm.pojo.TUser;
import com.zhang.crm.result.CodeEnum;
import com.zhang.crm.result.R;
import com.zhang.crm.service.RedisService;
import com.zhang.crm.util.JSONUtil;
import com.zhang.crm.util.ResponseUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ZhangLogoutSuccessHandler implements LogoutSuccessHandler {

    @Resource
    private RedisService redisService;
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //获取登录信息
        TUser tUser = (TUser) authentication.getPrincipal();
        //删除redis中的jwt
        Boolean delete = redisService.delete(Constants.REDIS_JWT_KEY + tUser.getId());

        //退出成功，返回json
        R r = R.OK(CodeEnum.LOGOUT_SUCCESS);

        //写入前端页面
        ResponseUtil.write(response,JSONUtil.toJSON(r));
    }
}
